var OAuth = require('oauth').OAuth;
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var extend = require('extend');
var Twitter = require('twitter-node-client').Twitter;

//Get this data from your twitter apps dashboard
var config = {
    "consumerKey": "",
    "consumerSecret": "",
    "callBackUrl": "http://xxx.com:3000/callback"
};

var accessToken = null;
var accessTokenSecret = null;

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
    secret: 'dddv4t4gg4'
}));

app.get('/', function (req, res) {
    if (!accessToken || !accessTokenSecret) {
        var oauth = new OAuth(
            "https://api.twitter.com/oauth/request_token",
            "https://api.twitter.com/oauth/access_token",
            config.consumerKey,
            config.consumerSecret,
            "1.0",
            config.callBackUrl,
            "HMAC-SHA1"
        );
        oauth.getOAuthRequestToken(function (error, oauth_token, oauth_token_secret, results) {
            if (error) {
                console.log(error);
                res.send("Authentication Failed!");
            }
            else {
                req.session.oauth_token = oauth_token;
                req.session.oauth_token_secret = oauth_token_secret;
                res.redirect('https://twitter.com/oauth/authenticate?oauth_token=' + oauth_token);
            }
        });
    } else {
        //Callback functions
        var error = function (err, response, body) {
            console.log(err);
            console.log('ERROR [%s]', err);
            res.send(err);
        };

        var twitter = new Twitter(extend({}, config, {
            "accessToken": accessToken,
            "accessTokenSecret": accessTokenSecret,
        }));

        var sendMsg = function (params, error, success) {
            var path = "/direct_messages/new.json";
            var url = twitter.baseUrl + path;
            twitter.doPost(url, params, error, success);
        };

        //Example calls
        twitter.getUserTimeline({screen_name: 'tongjun741', count: '10'}, error, function (data) {
            var rs = data;
            sendMsg({text: 'new message test', screen_name: 'tongjun741'}, error, function (data) {
                res.send(rs + data);
            });
        });
    }
});

app.get('/callback', function (req, res) {
    var oauth = new OAuth(
        "https://api.twitter.com/oauth/request_token",
        "https://api.twitter.com/oauth/access_token",
        config.consumerKey,
        config.consumerSecret,
        "1.0",
        config.callBackUrl,
        "HMAC-SHA1"
    );

    if (req.session.oauth_token && req.session.oauth_token_secret) {
        oauth.getOAuthAccessToken(
            req.session.oauth_token,
            req.session.oauth_token_secret,
            req.query.oauth_verifier,
            function (error, oauth_access_token, oauth_access_token_secret, results) {
                if (error) {
                    console.log(error);
                    res.send("Authentication Failure!");
                }
                else {
                    accessToken = oauth_access_token;
                    accessTokenSecret = oauth_access_token_secret;
                    req.session.screen_name = results.screen_name;
                    req.session.user_id = results.user_id;
                    res.redirect('/');
                }
            }
        );
    }
    else {
        res.redirect('/');
    }
});

app.post('/sendMsg', function (req, res) {
    if (req.body.passwd === '123456' && req.body.msg) {
        var to = req.body.to || "tongjun741";
        //Callback functions
        var error = function (err, response, body) {
            res.send(body);
        };
        var success = function (data) {
            res.send(data);
        };

        var twitter = new Twitter(extend({}, config, {
            "accessToken": accessToken,
            "accessTokenSecret": accessTokenSecret,
        }));

        var sendMsg = function (params, error, success) {
            var path = "/direct_messages/new.json";
            var url = twitter.baseUrl + path;
            twitter.doPost(url, params, error, success);
        };

        sendMsg({text: req.body.msg, screen_name: to}, error, success);
    } else {
        res.send("Failed");
    }
});

var server = app.listen(3000, function () {
    console.log('Listening on port %d', server.address().port);
});

